package org.example.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import lombok.Data;
import org.example.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


@ConfigurationProperties(prefix = "alipay")
@Component
@Data
public class AlipayUtil {
    @Autowired
    private OrdersService ordersService;
    // 应用ID appId
    private String appId;

    // 应用私钥，就是工具生成的应用私钥
//    @Value("${merchantPrivateKey}")
    private String merchantPrivateKey;

    // 字符编码格式
//    @Value("${alipay.charset}")  (UTF-8)
    private final String charset= "UTF-8";

    // 支付宝公钥,对应APPID下的支付宝公钥。根据应用公钥生成的支付宝公钥
//    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;

    //沙箱环境接口地址
    // 支付宝网关；https://openapi-sandbox.dl.alipaydev.com/gateway.do
    private String gatewayUrl;

    //(JSON)
    private final String format="JSON";

    // 签名方式
//    @Value("${alipay.signType}")(RSA2)
    private final String signType="RSA2";

    // 支付宝异步通知路径，付款完毕后会异步调用本项目方法，必须为公网地址，可以使用内网穿透地址
    // 支付宝会给我们发送一个请求，告诉我们支付成功的信息
//    @Value("${alipay.notifyUrl}")
    private String notifyUrl;
    //同步通知，支付成功，一般跳转到成功页,就是前端页面
//    @Value("${alipay.returnUrl}")
    private String returnUrl;

    //支付宝提供的接口
    private AlipayClient alipayClient=null;

        public String sendRequestToAlipay(String outTradeNo,Double totalAmount,String subject) throws AlipayApiException{
        //获得初始化的AlipayClient
        alipayClient=new DefaultAlipayClient(gatewayUrl,appId,merchantPrivateKey,format,charset,alipayPublicKey,signType);

        //设置请求参数
        AlipayTradePagePayRequest request=new AlipayTradePagePayRequest();
        request.setReturnUrl(returnUrl);
        request.setNotifyUrl(notifyUrl);

        //商品描述（可以为空）
        String body="";
        //商品的详细描述，对于订单的展示,会展示在页面上
        request.setBizContent("{\"out_trade_no\":\""+outTradeNo+"\","
                +"\"total_amount\":\""+totalAmount+"\"," +
                "\"subject\":\""+subject+"\"," +
                "\"body\":\""+body+"\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //获得响应，请求 得到表单数据
        String response=alipayClient.pageExecute(request).getBody();
        System.out.println("返回结果是："+response);
        return response;
    }


    //通过订单编号查询
    public  String query(String id){
        AlipayTradeQueryRequest request=new AlipayTradeQueryRequest();
        JSONObject bizContent=new JSONObject();
        bizContent.put("out_trade_no",id);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response=null;
        String body=null;
        try {
            response=alipayClient.execute(request);
            body=response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        }else{
            System.out.println("调用失败");
        }
        return body;
    }

}
